import { Inject, Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
import { ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { Observable } from 'rxjs';

import { LoggerService, UserService } from '../services';

/**
 * 用户登录，不再允许用户进入passport路由
 */
@Injectable({ providedIn: 'root' })
export class PassPortGuard implements CanActivate {
    constructor(private userSrv: UserService, public log: LoggerService, @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        const url: string = state.url;
        console.log(url);
        this.userSrv.redirectUrl = url;
        this.log.logMsg('验证是否已登录...', 'blue');
        // 判断是否有Token，如果有token，则不能进入passport相关页面
        const _token = this.tokenService.get();
        if (_token?.token) {
            return false;
        }

        this.log.logMsg('全部通过验证...', 'green');
        return true;
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
        return this.canActivate(route, state);
    }
}
